package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired(required = false)
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired(required = false)
    private ProvinceInfoMapper provinceInfoMapper;
    @Autowired(required = false)
    private CityInfoMapper cityInfoMapper;
    @Autowired(required = false)
    private DistrictInfoMapper districtInfoMapper;
    @Autowired(required = false)
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired(required = false)
    private LabelInfoMapper labelInfoMapper;
    @Autowired(required = false)
    private FeeValueMapper feeValueMapper;
    @Autowired(required = false)
    private GraphInfoMapper graphInfoMapper;
    @Autowired(required = false)
    private RoomInfoMapper roomInfoMapper;

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private GraphInfoService graphInfoService;

    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        // 查询省市区名称
        ProvinceInfo provinceInfo = provinceInfoMapper.selectById(apartmentSubmitVo.getProvinceId());
        CityInfo cityInfo = cityInfoMapper.selectById(apartmentSubmitVo.getCityId());
        DistrictInfo districtInfo = districtInfoMapper.selectById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());
        apartmentSubmitVo.setCityName(cityInfo.getName());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());

        // 1. 添加公寓的基本信息
        this.saveOrUpdate(apartmentSubmitVo);

        // 判断是否是更新
        boolean isUpdate =  apartmentSubmitVo.getId() != null;
        if (isUpdate) {
            // 若是更新，先删除再添加，此处删除
            // a. 删除公寓配套信息
            apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>()
                    .eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId()));

            // b. 删除公寓标签信息
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>()
                    .eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId()));

            // c. 删除公寓杂费信息
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>()
                    .eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId()));

            // d. 删除公寓图片信息
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>()
                    .eq(GraphInfo::getItemId, apartmentSubmitVo.getId())
                    .eq(GraphInfo::getItemType, ItemType.APARTMENT));
        }

        // 2. 添加公寓的相关信息
        // 2.1 添加公寓配套信息
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<ApartmentFacility> apartmentFacilityList = new ArrayList<>();
            facilityInfoIds.forEach(facilityInfoId -> {
                ApartmentFacility apartmentFacility = ApartmentFacility
                        .builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .facilityId(facilityInfoId)
                        .build();
                apartmentFacilityList.add(apartmentFacility);
            });
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }

        // 2.2 添加公寓标签信息
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)) {
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>();
            for(Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel
                        .builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .labelId(labelId)
                        .build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        // 2.3 添加公寓杂费信息
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            List<ApartmentFeeValue> apartmentFeeValues = new ArrayList<>();
            for(Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue
                        .builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .feeValueId(feeValueId)
                        .build();
                apartmentFeeValues.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValues);
        }

        // 2.4 添加公寓图片信息
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        // 等价于 if(graphVoList != null && graphVoList.size() > 0)
        if(!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo> graphInfoList = new ArrayList<>();
            graphVoList.forEach(graphVo -> {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfoList.add(graphInfo);
            });
            graphInfoService.saveBatch(graphInfoList);
        }
    }

    @Override
    public IPage<ApartmentItemVo> pageItem(Page<Object> objectPage, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageItem(objectPage, queryVo);
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        // 1. 查询公寓的基本信息
        ApartmentInfo apartmentInfo = this.getById(id);

        // 2. 查询公寓的相关信息
        // 2.1 查询公寓的配套信息
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);
        // 2.2 查询公寓的标签信息
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);
        // 2.3 查询公寓的杂费信息
        List<FeeValueVo> FeeValueVoList = feeValueMapper.selectListByApartmentId(id);
        // 2.4 查询公寓的图片信息
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemIdAndItemType(id, ItemType.APARTMENT);

        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        // BeanUtils.copyProperties(obj1, obj2) 将 obj1赋值给 obj2
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFeeValueVoList(FeeValueVoList);
        apartmentDetailVo.setGraphVoList(graphVoList);
        return apartmentDetailVo;
    }

    @Override
    public void removeByIdInfo(Long id) {
        // 没有房间的公寓才能被删除
        Long count = roomInfoMapper.selectCount(new LambdaQueryWrapper<RoomInfo>()
                                    .eq(RoomInfo::getApartmentId, id));
        if (count > 0) {
            // throw new RuntimeException("该公寓有房间，不能被删除");
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        // 删除公寓的基本信息
        this.removeById(id);

        // 删除公寓的相关信息
        // a. 删除公寓配套信息
        apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>()
                .eq(ApartmentFacility::getApartmentId,id));
        // b. 删除公寓标签信息
        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>()
                .eq(ApartmentLabel::getApartmentId, id));
        // c. 删除公寓杂费信息
        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>()
                .eq(ApartmentFeeValue::getApartmentId, id));
        // d. 删除公寓图片信息
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>()
                .eq(GraphInfo::getItemId, id)
                .eq(GraphInfo::getItemType, ItemType.APARTMENT));
    }
}




